Row Transposition Cipher

Module 01 / Lesson 08

Video Tutorial


The Matrix Permutation

Row Transposition is a much stronger transposition cipher than Rail Fence. It involves writing the plaintext in a grid row by row, and then reading the ciphertext column by column, but in a specific order determined by a Keyword.


Step-by-Step Process:

  1. Pick a keyword (e.g., "HACK").
  2. Number the letters of the keyword based on their alphabetical order (A=1, C=2, H=3, K=4).
  3. Write the message in rows under these numbers.
  4. Read off the columns starting from column 1, then column 2, and so on.

Example: "CIPHERBOY" (Key: 3 1 4 2)

Key Order:
3   1   4   2
C   I   P   H
E   R   B   O
Y   X   X   X

Result (Read Col 1, then 2, 3, 4): "IRXHOXCEYPBX"


Python Implementation

def row_transposition_encrypt(text, key):
    # Determine order based on keyword alphabetization
    order = sorted(range(len(key)), key=lambda k: key[k])
    
    # Padding if necessary
    while len(text) % len(key) != 0:
        text += 'X'
        
    # Build columns based on the order
    ciphertext = ""
    for index in order:
        for i in range(index, len(text), len(key)):
            ciphertext += text[i]
            
    return ciphertext

# Usage
print(row_transposition_encrypt("CIPHERBOY", "HACK"))